package com.edu.cdp.service.impl;

import com.edu.cdp.config.OssConfig;
import com.edu.cdp.service.CommonService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private OssConfig ossConfig;

    @Value("${spring.mail.username}")
    private String from;
    @Override
    public String upload(MultipartFile file) {
        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId,accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装OSS上存储的路径
        String folder = dft.format(time);
        String fileName = String.valueOf(UUID.randomUUID());
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = "SupermarketCashier/" + folder + "/" + fileName + extension;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                return "https://"+bucketName+"."+endPoint+"/"+uploadFileName;
            }
        } catch (IOException e) {
           log.error("文件上传失败：" + e.getMessage());
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        return null;
    }

    @Override
    public void sendMail(String email, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);

        helper.setFrom(from);
        helper.setTo(email);
        helper.setSubject(subject);
        helper.setText(content, true);
        } catch (MessagingException e) {
            log.error("邮件发送失败");
            throw new RuntimeException(e);
        }
        // 发送邮件
        mailSender.send(message);
    }

    @Override
    public void sendPayMessage(String email, String username, Double money) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);

            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject("支付成功通知");
            helper.setText("尊敬的" + username + "：您在本超市成功消费" + money + "元，祝您生活愉快！", true);
        } catch (MessagingException e) {
            log.error("邮件发送失败");
            throw new RuntimeException(e);
        }
        // 发送邮件
        mailSender.send(message);
    }
    }
